import { login, getLeftMenu } from '@/api/api'
import { getUserInfo, setUserInfo, removeUserInfo } from '@/utils/auth'
import Cookies from 'js-cookie'
// import Layout from '@/views/layout/Layout'
// import RouterView from '@/views/main/router'
import axios from 'axios'
import * as _ from 'lodash'
import store from "../index";
const qs= require('qs');

function getChildMenu(childList){
  if(childList.length>0){
    let arr = [];
    for(let k=0;k<childList.length;k++){
      var menuObj = {
        path: childList[k].code,
        name: childList[k].code,
        meta: { title: childList[k].name, icon: childList[k].icon }
      };

      if (childList[k].hasOwnProperty("childList")
        && childList[k]["childList"] != null
        && childList[k]["childList"].length > 0) {
        menuObj.component = RouterView;
        menuObj.redirect = "noredirect";
        menuObj.children = getChildMenu(childList[k]["childList"]);
      } else {
        if (childList[k].isMenu==1 && childList[k].chartPageId>0 && childList[k].useOpen==0) {//如果不是菜单，使用iframe方式浏览报表系统页面
          menuObj.component = loadView("main/chartPageView");
          menuObj.name = childList[k].code + ":" + childList[k].chartPageId;
        }else if(childList[k].isMenu==1 && childList[k].chartPageId>0 && childList[k].useOpen==1){//如果不是菜单，使用open窗口方式浏览报表系统页面
        }else if(childList[k].isMenu==1 && childList[k].requestUrl!="" && childList[k].requestUrl.length>0 && childList[k].useOpen==0){//如果不是菜单，使用iframe方式浏览外链
        }else if(childList[k].isMenu==1 && childList[k].requestUrl!="" && childList[k].requestUrl.length>0 && childList[k].useOpen==1){//如果不是菜单，使用open窗口方式浏览外链
        }else {
          menuObj.component = loadView(childList[k].vuePath);
        }
      }

      arr.push(menuObj);
    }
    return arr;
  }else {
    return [];
  }
}

export const loadView = (view) => { // 路由懒加载
  return () => import(`@/views/${view}`)
}

const user = {
  state: {
    // roles: getUserInfo() ? JSON.parse(getUserInfo()) : {}, //登录角色信息
    // system: Cookies.get('systemCookies') ? JSON.parse(Cookies.get('systemCookies')) : null,  //系统信息
    // osType: Cookies.get('osTypeCookies') ? Cookies.get('osTypeCookies') : null,  //当前系统类别
    menus: [],
    defaultOpenMenu: null,
    workAreaHeight: null
  },

  mutations: {
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_SYSTEM: (state, system) => {
      state.system = system;
    },
    SET_OSTYPE: (state, type) => {
      state.osType = type;
    },
    SET_MENUS: (state, menus) => {
      state.menus = menus;
    },
    SET_DEFAULT_OPEN_MENU: (state, defaultOpenMenu) => {
      state.defaultOpenMenu = defaultOpenMenu;
    },
    SET_WORK_AREA_HEIGHT: (state, workAreaHeight) => {
      state.workAreaHeight = workAreaHeight;
    }
  },

  actions: {
    //授权登录-获取系统信息
    AuthLogin({commit, state},code){
      axios.post(authInfo.authUrl + '/oauth/token', {
        grant_type: 'authorization_code',
        code: code,
        client: authInfo.appId,
        redirect_uri: authInfo.baseUrl
      }, {
        transformRequest: [function (data) {
          return qs.stringify(data)
        }],
        auth: {
          username: authInfo.appId,
          password: authInfo.appSecret
        }
      })
        .then(response => {
          if(response.user_info && response.user_info.osList){

            const data = _.cloneDeep(response.user_info);
            delete data.osList;
            data.Authorization = response.access_token;
            setUserInfo(data); //js-cookies缓存
            Cookies.set('systemCookies',response.user_info.osList);
            Cookies.set('osTypeCookies',response.user_info.osList[0].code);
            commit('SET_ROLES', data); //状态管理
            commit('SET_SYSTEM', response.user_info.osList); //系统类别信息
            commit('SET_OSTYPE', response.user_info.osList[0].code); //osType
          }
          window.location.href = authInfo.baseUrl
        })
        .catch(err => {
          console.error(err)
        })
    },
    // 登录
    Login({ commit }, loginInfo) {
      return new Promise((resolve, reject) => {
        login({account: loginInfo.username.trim(),password:loginInfo.password}).then(response => {
          if(response.code && response.code === 200){
            const data = response.data;
            data.user.loginInfo=loginInfo;
            setUserInfo(data.user); //js-cookies缓存
            Cookies.set('systemCookies',data.system);
            Cookies.set('osTypeCookies',data.system[0].code);
            commit('SET_ROLES', data.user); //状态管理
            commit('SET_SYSTEM', data.system); //系统类别信息
            commit('SET_OSTYPE', data.system[0].code); //osType
            global.loginError=null;
          }else{
            global.loginError = response;
          }
          resolve();
        }).catch(error => {
          reject(error);
        })
      })
    },
    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_ROLES', null);
        commit('SET_MENUS', []);
        removeUserInfo();
        Cookies.remove('systemCookies');
        Cookies.remove('osTypeCookies');
        Cookies.remove('buttonCookies');
        // window.location.href = authInfo.authUrl + '/logout';
        resolve()
      })
    },
    //osType更新
    getOSType: ({ commit },data) => {
      commit('SET_OSTYPE',data);
    },
    getMenus({ commit }) {
      const params = {"code": user.state.osType,"userId":store.getters.roles.id};
      return new Promise((resolve, reject) => {
        getLeftMenu(params).then(response => {
          if (response.code && response.code === 200) {
            let menuList = response.data.data.data;
            //console.log(JSON.stringify(response.data))
            let routerArr = [];
            for (let i = 0; i < menuList.length; i++) {
              var menuObj = {
              };
              if (menuList[i].vuePath.indexOf("http")>-1) {
                //menuObj.path = menuList[i].vuePath;
              }else{
                if (menuList[i].hasOwnProperty("childList")
                  && menuList[i].childList != null
                  && menuList[i].childList.length > 0) {
                  menuObj.path = '/' + menuList[i].code;
                  menuObj.name = menuList[i].code;
                  menuObj.meta = {title: menuList[i].name, icon: menuList[i].icon};
                  menuObj.component = Layout;
                  menuObj.redirect = "noredirect";
                  menuObj.children = getChildMenu(menuList[i].childList);
                } else {
                  menuObj.path = '/' + menuList[i].code;
                  menuObj.meta = { title: menuList[i].name, icon: menuList[i].icon };
                  menuObj.component = Layout;
                  menuObj.children = [{
                    path: 'index',
                    name: menuList[i].code,
                    component: loadView(menuList[i].vuePath),
                    meta: { title: menuList[i].name, icon: menuList[i].icon }
                  }]
                }
                routerArr.push(menuObj);
              }
            }
            user.state.defaultOpenMenu = ["/" + menuList[0].code];// 设置默认展开菜单
            commit('SET_MENUS', routerArr);
            commit('SET_BUTTON', response.data.actions); //通知更新button
            let workHeight =document.documentElement.clientHeight-157;
            commit('SET_WORK_AREA_HEIGHT', `${workHeight}`);
          }
          resolve();
        }).catch(error => {
          console.log(error);
          reject(error)
        })
      })
    }
  }
};

export default user
